package com.tiankun.eurekauserinfo.controller;

import com.tiankun.eurekauserinfo.exception.BusinessException;
import com.tiankun.eurekauserinfo.pojo.Attention;
import com.tiankun.eurekauserinfo.proxy.ShopHandler;
import com.tiankun.eurekauserinfo.service.AttentionService;
import com.tiankun.eurekauserinfo.utils.JsonResult;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * User: bear
 * Date: 2020/11/12
 * Description
 * Version: V1.0
 */
@RestController
@RequestMapping("attention")
@CrossOrigin   //用于实现跨域的注解
public class AttentionController {

    @Resource
    private AttentionService attentionService;
    @Resource
    private ShopHandler shopHandler;


    @PostMapping(value = "add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map add(@RequestBody Map<String, Integer> map) {
        JsonResult jsonResult = new JsonResult();
        Integer add = attentionService.add(map.get("userId"), map.get("shopId"));
        if (add == 1) {
            jsonResult.setCode("200");
            jsonResult.setMsg("关注成功");
        } else {
            throw new BusinessException("系统开小差了");
        }
        return jsonResult.getValues();
    }

    @PostMapping(value = "delete", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map delete(@RequestBody Map<String, Integer> map) {
        JsonResult jsonResult = new JsonResult();
        Integer add = attentionService.delete(map.get("userId"), map.get("shopId"));
        if (add == 1) {
            jsonResult.setCode("200");
            jsonResult.setMsg("取消关注成功");
        } else {
            throw new BusinessException("系统开小差了");
        }
        return jsonResult.getValues();
    }

    @PostMapping(value = "getList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map getList(@RequestBody Map<String, Integer> map) {
        List<Map<String, Object>> allShop = new ArrayList<>();
        JsonResult jsonResult = new JsonResult();
        //获取到所有的店铺信息
        List<Attention> attentions = attentionService.getList(map.get("userId"));
        for (Attention attention : attentions) {
            //遍历循环所有关注信息
            //用店铺id对店铺进行查询（跨模块）得到店铺信息的map集合
            //通信获取店铺信息
            Map shop = shopHandler.selectById(attention.getShopId());
            //得到店铺信息进行用List集合记录
            allShop.add(shop);
        }
        jsonResult.setCode("200");
        jsonResult.setMsg("所有关注的店铺信息");
        jsonResult.setData(allShop);
        return jsonResult.getValues();
    }
}
